package com.jmu.edu.IMApplication.fragment;

import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.aip.util.Base64Util;
import com.google.android.material.button.MaterialButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jmu.edu.IMApplication.MyApplication;
import com.jmu.edu.IMApplication.R;
import com.jmu.edu.IMApplication.adapter.ChatItemAdapter;
import com.jmu.edu.IMApplication.adapter.CustomTextItemAdapter;
import com.jmu.edu.IMApplication.bean.ChatRecord;
import com.jmu.edu.IMApplication.bean.GestureAndFaceResult;
import com.jmu.edu.IMApplication.event.LoadCustomText;
import com.jmu.edu.IMApplication.event.NotifyToSendMessageEvent;
import com.jmu.edu.IMApplication.event.SendMessageEvent;
import com.jmu.edu.IMApplication.event.SwitchFragmentEvent;
import com.jmu.edu.IMApplication.gen.ChatRecordDao;
import com.jmu.edu.IMApplication.net.bean.Identify;
import com.jmu.edu.IMApplication.net.bean.Text;
import com.jmu.edu.IMApplication.net.bean.UserIdentify;
import com.jmu.edu.IMApplication.utils.FileUtil;
import com.jmu.edu.IMApplication.utils.GetAccessUtils;
import com.jmu.edu.IMApplication.utils.GsonUtils;
import com.jmu.edu.IMApplication.utils.HttpUtil;
import com.jmu.edu.IMApplication.utils.ImageTools;
import com.jmu.edu.IMApplication.utils.MsgUtils;
import com.jmu.edu.IMApplication.utils.ViewUtils;
import com.jmu.edu.IMApplication.utils.WillowUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.event.MessageEvent;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class ChatFragment extends Fragment {

    private static final String TAG = "chat";
    private MaterialButton backButton, sendButton, distinguishButton, addButton, moreButton;
    private String backTag = null;

    private EditText inputText;
    private RecyclerView recyclerView;
    private TextView usernameText, stateText;
    private ChatItemAdapter adapter;
    private List<Message> messageList = new ArrayList<>();
    private String friendName, state, username;
    private Bitmap friendAvatar;
    // 表示跳转到相机
    public static final int RC_TAKE_PHOTO = 1;
    public int isOver = 0;
    private String mTempPhotoPath;
    private Uri imageUri;
    private File photoFile;
    private String filename;
    // 显示ChatFunctionFragment时候的灰度背景
    private View addDetailsBackground;

    /**
     * 显示自定义文字的popupWindow的控件
     */
    private PopupWindow popupWindow;
    private LinearLayout linearLayout;
    private CustomTextItemAdapter popupWindowAdapter;
    private RecyclerView popupWindowRecyclerView;


    public void setFriendAvatar(Bitmap friendAvatar) {
        this.friendAvatar = friendAvatar;
    }


    public ChatFragment() {
        // Required empty public constructor
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSwitchFragmentEvent(SwitchFragmentEvent event) {
        if (event.getHideTag().equals("chat")) {
            //调用该事件，关闭ChatFunctionFragment
            addDetailsBackground.callOnClick();
            CustomTextFragment customTextFragment = (CustomTextFragment) event.getShowFragment();
            customTextFragment.setGestureAndFaceResultList(MyApplication.getGestureAndFaceResultList());
            ViewUtils.hideFragment(ChatFragment.this, event.getShowFragment(), event.getShowTag(), R.anim.from_right, R.anim.out_left);
        }


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loadInputText(LoadCustomText loadCustomText) {
        inputText.setText(loadCustomText.getContent());
        sendButton.callOnClick();
        popupWindow.dismiss();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSendMessageEvent(SendMessageEvent event) throws FileNotFoundException {
        if (event.getMessageType() == NotifyToSendMessageEvent.IMAGE_TYPE) {
            File file = (File) event.getMessageContent();
            if (file != null) {
                Message message = MsgUtils.createSingleImageMessage(username, file, new BasicCallback() {
                    @Override
                    public void gotResult(int i, String s) {
                        if (i == 0) {
                            Toast.makeText(getContext(), "发送成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getContext(), "发送失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                MsgUtils.sendMessage(message);
                messageList.add(message);
                adapter.notifyItemInserted(messageList.size() - 1);
                //添加完使recyclerview定位到底部
                recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
                //添加完将ChatFunction隐藏
                addDetailsBackground.callOnClick();
            } else {
                Toast.makeText(getContext(), "没有要发送的文件", Toast.LENGTH_SHORT).show();
            }
        } else if (event.getMessageType() == NotifyToSendMessageEvent.TEXT_TYPE) {
            String text = (String) event.getMessageContent();
            StringBuilder stringBuilder = new StringBuilder(inputText.getText().toString());
            stringBuilder.append(text);
            inputText.setText(stringBuilder.toString());
            inputText.requestFocus();
            inputText.setSelection(stringBuilder.length());
            addDetailsBackground.callOnClick();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        //这里增加回退监听
        ViewUtils.addBackListenerForHide(getView(), backButton);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_chat, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
    }


    private void initView() {
        distinguishButton = getView().findViewById(R.id.fragment_chat_distinguish);
        addButton = getView().findViewById(R.id.fragment_chat_add);
        backButton = getView().findViewById(R.id.fragment_chat_back);
        sendButton = getView().findViewById(R.id.fragment_chat_send);
        moreButton = getView().findViewById(R.id.fragment_chat_more);
        addDetailsBackground = getView().findViewById(R.id.fragment_chat_add_details_background);
        initListener();
        inputText = getView().findViewById(R.id.fragment_chat_input);
        usernameText = getView().findViewById(R.id.fragment_chat_username);
        stateText = getView().findViewById(R.id.fragment_chat_state);
        linearLayout = getView().findViewById(R.id.fragment_chat_message);
        recyclerView = getView().findViewById(R.id.fragment_chat_recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        // 设置从底部开始加载
        linearLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(linearLayoutManager);
        //loadData要调用两次，一个是这个Fragment第一次创建的时候，也就是这里，另一个就是在onHiddenChanged
        loadData();

        //创建用来展示用的popupWindow
        createTextWindow();
        Log.d("聊天界面", "初始化view完毕");


    }


    private void initListener() {
        moreButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WillowUtils.getUserInfo(username, new GetUserInfoCallback() {
                    @Override
                    public void gotResult(int i, String s, UserInfo userInfo) {
                        String tag = "showUser";
                        ShowUserFragment showUserFragment = (ShowUserFragment) MyApplication.fragmentManager.findFragmentByTag(tag);
                        if (showUserFragment == null) {
                            showUserFragment = new ShowUserFragment();
                        }
                        // 设置必须的属性--userInfo以及backTag
                        showUserFragment.setUserInfo(userInfo);
                        Bundle bundle = new Bundle();
                        bundle.putString("backTag", "chat");
                        showUserFragment.setArguments(bundle);
                        ViewUtils.hideFragment(ChatFragment.this, showUserFragment, tag, R.anim.from_right, R.anim.out_left);
                    }
                });
            }
        });
        // 回退按钮
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (backTag != null) {
                    Fragment show = MyApplication.fragmentManager.findFragmentByTag(backTag);
                    ViewUtils.hideFragment(ChatFragment.this, show, backTag, R.anim.from_left, R.anim.out_right);
                } else {
                    ViewUtils.hideFragment(ChatFragment.this, R.anim.from_right, R.anim.out_right);
                }

            }
        });
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取文本框输入内容
                String message = inputText.getText().toString();
                // 如果message不为空，那么将这条message存储在本地数据库,且根据存储的聊天记录长度是否>10000，来决定是否上传到服务器进行预处理
                if (!message.isEmpty()) {
                    saveChatRecordInGreenDao(message);
                }
                //将文本框输入内容构建成Message
                Message newMessage = MsgUtils.createSingleTextMessage(username, message, new BasicCallback() {
                    @Override
                    public void gotResult(int i, String s) {
                        // 该消息没有发送成功
                        if (i != 0) {
                            Toast.makeText(getContext(), "消息发送失败" + s, Toast.LENGTH_SHORT).show();
                        } else {
                            ((MessageFragment) (MyApplication.getFragmentList().get(0))).refreshData();  //刷新会话列表
                            Toast.makeText(getContext(), "消息发送成功" + s, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                // 发送该消息
                MsgUtils.sendMessage(newMessage);
                // 将该消息添加到消息列表中用于展示
                messageList.add(newMessage);
                // 适配器告知有item插入，要添加视图
                adapter.notifyItemInserted(messageList.size() - 1);
                //添加完使recyclerview定位到底部
                recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
                // 将消息重新设置为空
                inputText.setText("");
            }
        });
        //添加手势识别按钮的事件
        distinguishButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentToTakePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                int sdkVersion = Build.VERSION.SDK_INT;
                //识别API29 及以上版本
                if (sdkVersion >= 29) {
                    imageUri = createImageUri();
                    mTempPhotoPath = Environment.getExternalStorageDirectory() + File.separator + "Pictures/preventpro" + File.separator + filename + ".jpg";
                    photoFile = new File(getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES), filename + ".jpg");
                } else {
                    File fileDir = new File(Environment.getExternalStorageDirectory() + File.separator + "photoTest" + File.separator);
                    photoFile = new File(fileDir, "photo.jpeg");
                    mTempPhotoPath = photoFile.getAbsolutePath();
                    imageUri = FileProvider.getUriForFile(getActivity(), "com.jmu.edu.IMApplication.FileProvider", photoFile);
                }
                intentToTakePhoto.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intentToTakePhoto, RC_TAKE_PHOTO);
            }
        });
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showChatFunctionFragment();
            }
        });
        addDetailsBackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //实现点击外部自动关闭已经打开的更多功能的fragment功能
                ChatFunctionFragment chatFunctionFragment = (ChatFunctionFragment) getChildFragmentManager().findFragmentByTag("chatFunction");
                if (chatFunctionFragment != null && chatFunctionFragment.isVisible()) {
                    getChildFragmentManager().beginTransaction().hide(chatFunctionFragment).commit();
                    hideGreyBackground();
                }

            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            MsgUtils.exitConversation();
            WillowUtils.unRegisterEventReceiver(this);
            EventBus.getDefault().unregister(this);
        } else {
            loadData();
            ViewUtils.addBackListenerForHide(getView(), backButton);
        }
    }

    public void loadData() {
        Bundle bundle = getArguments();
        username = bundle.getString("username");
        friendName = bundle.getString("friendName");
        state = bundle.getString("state");
        // backTag用来判断ChatFragment隐藏后会显示哪一个Fragment, null则代表无需显示
        backTag = bundle.getString("backTag", null);

        //注册事件订阅
        WillowUtils.registerEventReceiver(this);
        EventBus.getDefault().register(this);

        // 进入单聊状态，取消接收对应用户的聊天事件
        MsgUtils.enterSingleConversation(username);

        messageList = MsgUtils.getMessageList(username);
        MsgUtils.enterSingleConversation(username);
        if (adapter == null) {
            adapter = new ChatItemAdapter();
        }
        adapter.setMessageList(messageList);
        // 如果recycleView 不为空且还没有装载适配器，那么装载适配器，否则直接更新视图
        if (recyclerView.getAdapter() == null) {
            recyclerView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        if (adapter.getItemCount() != 0) {
            // 定位到最后一条信息
            recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
        }

        //设置展示的用户昵称
        usernameText.setText(friendName);
        stateText.setText(state);

        Log.d("聊天界面", "加载数据完毕，与该好友的聊天记录数量为:" + messageList.size());
    }

    public void onEventMainThread(MessageEvent messageEvent) {
        //获取新消息列表
        Message message = messageEvent.getMessage();
        Log.d("好友聊天界面对话监听", "收到了消息:" + message.getContent().toJson());
        messageList.add(message);
        adapter.notifyItemInserted(messageList.size() - 1);
        //添加完使recyclerview定位到底部
        recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult: 获得照片的bitmap");
        inputText.requestFocus();
        Bitmap bitmap = ImageTools.getBitmap(mTempPhotoPath);
        ImageTools.saveBitmap(bitmap, photoFile);
        //释放bitmap资源
        bitmap.recycle();
        try {
            gesture();
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
    }

    private Uri createImageUri() {
        ContentValues contentValues = new ContentValues();
        filename = System.currentTimeMillis() + "";
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, filename + "");
        //兼容Android Q和以下版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/preventpro");
        }
        //设置文件类型
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/JPEG");
        Uri uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        return uri;
    }

    public void gesture() throws IOException, JSONException {
        // 如果进行手势识别，那么清空之前的预设文本
        changePopupWindowContent(new ArrayList<>(), true);
        Log.d(TAG, "gesture: api识别开始");
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/gesture";
        byte[] imgData = FileUtil.readFileByBytes(photoFile.getAbsolutePath());
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");
        String param = "image=" + imgParam;
        //手势识别
        new Thread(new Runnable() {
            @Override
            public void run() {
                String accessToken = GetAccessUtils.getAuth("Mq9rTp1LQNAt3HCdf9T4bvSw", "p8XEGdG1Q7eGkphQV7xigT4AGYsMGdb4");
                try {
                    String result = HttpUtil.post(url, accessToken, param);
                    JSONObject jsonObject = new JSONObject(result);
                    int number = Integer.parseInt(jsonObject.getString("result_num"));
                    // 遍历结果，查看是否匹配到对应的手势
                    for (int i = 0; i < number; i++) {
                        String classname = jsonObject.getJSONArray("result").getJSONObject(i).get("classname").toString();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                handleIdentifyResult(classname);
                            }
                        });

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        //面部表情识别
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = "https://aip.baidubce.com/rest/2.0/face/v3/detect";
                try {
                    Map<String, Object> map = new HashMap<>();
                    map.put("image", imgStr);
                    map.put("face_field", "emotion");
                    map.put("image_type", "BASE64");
                    String param = GsonUtils.toJson(map);
                    // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
                    String accessToken = GetAccessUtils.getAuth("bMlPz47YhkwcBOxckpOhNimT", "wY6XGwO3qvdz7NmjS6TN5WlVcafQWero");
                    String result = HttpUtil.post(url, accessToken, "application/json", param);
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.getJSONObject("result") != null) {
                        String emotion = jsonObject.getJSONObject("result").getJSONArray("face_list")
                                .getJSONObject(0).getJSONObject("emotion").get("type").toString();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                handleIdentifyResult(emotion);
                            }
                        });

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 将手势/表情api识别到的结果进行比对，如果满足条件那么就展示预设文本
     *
     * @param identifyName api识别的结果
     */
    private void handleIdentifyResult(String identifyName) {
        Log.d(TAG, "handleIdentifyResult: " + identifyName);

        //isOver是用来判断是否api测试全部完毕
        isOver++;
        if (MyApplication.getIdentifyList() != null) {
            for (GestureAndFaceResult result : MyApplication.getGestureAndFaceResultList()) {
                Log.d(TAG, "english:" + result.getIdentify().getEnglishName() + "||" + identifyName);
                //满足该条件说明匹配成功，找到了预设文本的列表
                if (result.getIdentify().getEnglishName().equals(identifyName)) {
                    Toast.makeText(getContext(), "检测到" + result.getIdentify().getChineseName(), Toast.LENGTH_SHORT).show();
                    List<String> textList = new ArrayList<>();
                    // 遍历预设文本列表，提取出来预设文本的文字内容
                    for (UserIdentify userIdentify : result.getUserIdentifyList()) {
                        textList.add(userIdentify.getIdentifyText());
                    }
                    // 改变popupWindow展示的文字
                    changePopupWindowContent(textList, false);
                    showTextWindow();
                    // 如果成功找到，那么isOver--,如果一个api成功识别+有预设文本，那么isOver相当于没有变化
                    isOver--;
                    return;
                }
                // 如果isOver为2，说明两个api的识别结果都没有预设文本，那么这个时候需要toast来提示
                if (isOver == 2) {
                    Toast.makeText(getContext(), "没有检测到对应的预设文本，请您设置该手势/表情对应的文本", Toast.LENGTH_SHORT).show();
                    showTextWindow();
                    popupWindow.dismiss();
                    isOver = 0;
                }
            }
        } else {
            // 如果没有获得identifyList，说明前面服务器连接异常，重新向服务器获取数据
            Toast.makeText(getContext(), "服务器连接异常，请重新操作", Toast.LENGTH_SHORT).show();

        }

    }


    private void showTextWindow() {
        // 如果这个时候没有展示，那么展示
        if (!popupWindow.isShowing()) {
            // 展示的位置位于linearLayout下方
            popupWindow.showAsDropDown(linearLayout, 0, -500, Gravity.TOP);
        }

        //popupWindow.showAtLocation(recyclerView, Gravity.BOTTOM, 0, 140);
    }

    private void changePopupWindowContent(List<String> contentList, boolean isReset) {
        if (isReset) {
            popupWindowAdapter.setContentList(contentList);
        } else {
            popupWindowAdapter.addContentList(contentList);
        }
        if (popupWindowRecyclerView.getAdapter() != null) {
            popupWindowAdapter.notifyDataSetChanged();
        } else {
            popupWindowRecyclerView.setAdapter(popupWindowAdapter);
        }

    }

    private void createTextWindow() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_chat_popupwindow, null);
        // 设置RecycleView
        popupWindowRecyclerView = view.findViewById(R.id.layout_chat_popupwindow_recyclerView);
        // 设置为垂直排列
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        popupWindowRecyclerView.setLayoutManager(linearLayoutManager);
        //创建适配器并添加数据
        popupWindowAdapter = new CustomTextItemAdapter();
        // 这个同样可以用来初始化内容
        changePopupWindowContent(new ArrayList<>(), true);


        // 第一个参数popupWindow的View，后面两个参数一个是宽度(设置为linearLayout宽度一样),一个是高度
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置获取焦点+可以获得点击事件
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        // 设置点击外部可以关掉
        popupWindow.setOutsideTouchable(true);


        // 设置popupWindow消失时候的监听器，用来将nameToggleButton还原到noChecked状态
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
            }
        });

    }

    private void showChatFunctionFragment() {
        //在manager中查找是否已经有该fragment
        ChatFunctionFragment chatFunctionFragment = (ChatFunctionFragment) getChildFragmentManager().findFragmentByTag("chatFunction");
        if (chatFunctionFragment != null) {
            //如果正在显示，那么隐藏这个fragment
            if (chatFunctionFragment.isVisible()) {
                getChildFragmentManager().beginTransaction().hide(chatFunctionFragment).commit();
                //要重现实现隐藏的输入栏部分
                hideGreyBackground();
            } else if (chatFunctionFragment.isAdded()) {
                //如果已经添加，那么show即可，否则添加
                getChildFragmentManager().beginTransaction().show(chatFunctionFragment).commit();
                showGreyBackground();
            } else {
                getChildFragmentManager().beginTransaction().add(chatFunctionFragment, "chatFunction").commit();
                showGreyBackground();
            }
        } else {
            //如果不存在这个fragment，则直接new一个add进去
            getChildFragmentManager().beginTransaction()
                    .add(R.id.fragment_chat_add_details, new ChatFunctionFragment(), "chatFunction").commit();

            showGreyBackground();
        }

    }

    /**
     * 将输入栏和发送那一栏隐藏，将灰度背景显示出来
     */
    private void showGreyBackground() {
        linearLayout.setVisibility(View.GONE);
        sendButton.setVisibility(View.GONE);

        addDetailsBackground.setVisibility(View.VISIBLE);
    }

    /**
     * 将输入栏和发送那一栏重新显示，隐藏灰度背景
     */
    private void hideGreyBackground() {
        linearLayout.setVisibility(View.VISIBLE);
        sendButton.setVisibility(View.VISIBLE);
        addDetailsBackground.setVisibility(View.GONE);
    }

    /**
     * 将聊天记录保存在本地数据库GreenDao中，如果记录已经超过10000的长度，那么发送到服务端进行处理，并清空记录的数据
     *
     * @param message 要保存的新的聊天记录
     */
    private void saveChatRecordInGreenDao(String message) {
        // 获取本地存储的聊天记录数据
        ChatRecord chatRecord = MyApplication.getChatRecordDao().queryBuilder()
                .where(ChatRecordDao.Properties.Username.eq(MyApplication.getUser().getUserName()))
                .unique();
        // 得到新增文本后的聊天记录长度
        int length = chatRecord.appendText(message);
        // 如果长度 > 10000， 那么发送到服务器进行分词预处理
        if (length > 10000) {
            Text text = new Text();
            text.setUserText(chatRecord.getText());
            text.setUsername(chatRecord.getUsername());
            RequestBody requestBody = RequestBody.create(HttpUtil.JSON, new Gson().toJson(text));
            Request request = new Request.Builder().url(HttpUtil.URL_WORD_CUT).post(requestBody).build();
            MyApplication.getClient().newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "onFailure: word_cut", e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.d(TAG, "onResponse: word_cut_success" + response.body().string());
                    // 处理完成以后，清空本地存储的聊天记录
                    chatRecord.setText("");
                    MyApplication.getChatRecordDao().update(chatRecord);
                }
            });
        } else {
            // 更新本地存储的聊天记录
            MyApplication.getChatRecordDao().update(chatRecord);
        }

    }

}